package com.magupe.im.web.handler.websocket;

import com.magupe.im.web.db.service.DataService;
import com.magupe.im.web.protocol.request.MessageRequest;
import com.magupe.im.web.protocol.response.MessageResponse;
import com.magupe.im.web.protocol.response.ResponseStatus;
import com.magupe.im.web.protocol.response.StatusCode;
import com.magupe.im.web.session.SessionUtils;
import com.magupe.im.web.utils.UUIDUtil;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class WebsocketMessageHandler extends SimpleChannelInboundHandler<MessageRequest> {

    protected Logger logger = LoggerFactory.getLogger(WebsocketMessageHandler.class);

    private DataService dataService;

    public WebsocketMessageHandler(DataService dataService){
        this.dataService = dataService;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, MessageRequest request) throws Exception {
        // 1.设置id
        request.setId(UUIDUtil.getUuid());

        // 2.封装消息体
        request.setFromId(request.getUserId());
        request.setStatusCode(StatusCode.MESSAGE_SEND_SUCCESS);

        // 3.给消息接收人发送消息，获取接收人的channel，并判断channel是否存在，不存在则缓存消息
        Channel channel = SessionUtils.getChannel(request.getAppId(), request.getReceiverId());
        if(null != channel){
            logger.debug("websocket signal communication. user channelId: {}", ctx.channel().id().toString());
            logger.debug("websocket signal communication. receiver channelId: {}", channel.id().toString());
            ChannelFuture future = channel.writeAndFlush(new TextWebSocketFrame(request.toString()));
            // 如果消息发送失败，需要缓存消息
            dataService.cacheMessage(future, request);
        } else {
            dataService.saveMessage(request);
        }

        // 4.返回应答消息给客户端，表明消息服务器已经接受到了
        MessageResponse  response = new MessageResponse(ResponseStatus.MESSAGE_SEND_REPLY_SUCCESS);
        ctx.channel().writeAndFlush(new TextWebSocketFrame(response.toString()));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        logger.error("websocket signal communication. error: {}", cause);
        ctx.close();
    }
}
